<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="离职类型及原因设置"
        :breadCrumb="['人事', '基础设置', '离职设置', '离职类型及原因设置']"
        show-back
      ></pageHeaderNew>
    </template>
    <div class="wrap">
      <div class="left-list">
        <div @click="collapse" class="collapseBtn">
          <IconCaretRight v-if="isCollapsed" />
          <IconCaretLeft v-else />
        </div>
        <a-layout class="layout-demo">
          <a-layout-sider
            collapsible
            breakpoint="xl"
            hide-trigger
            :collapsed="isCollapsed"
            :collapsed-width="0"
          >
            <div v-show="!isCollapsed">
              <div class="header">
                <span class="title">离职类型</span>
                <a-button type="text" @click="addType">新增</a-button>
              </div>
              <a-scrollbar style="height: 600px; overflow: auto">
                <div class="scroll">
                  <div
                    class="scroll-item"
                    v-for="item in typeList"
                    :key="item.id"
                    @click="itemClick(item.id)"
                    :class="currId === item.id ? 'item-active' : ''"
                  >
                    <div>{{ item.name }}</div>
                    <div>
                      <a-tooltip content="编辑">
                        <IconFont
                          type="icon-edit"
                          :size="26"
                          :style="{
                            cursor: 'pointer'
                          }"
                          @click.stop="goEditType(item)"
                        />
                      </a-tooltip>
                      <a-tooltip content="删除" v-if="item.sysDefault !== 1">
                        <a-popconfirm
                          content="是否确认删除该条数据?"
                          @ok="delType(item.id)"
                        >
                          <IconFont
                            type="icon-delete"
                            :size="26"
                            :style="{
                              cursor: 'pointer'
                            }"
                            @click.stop
                          />
                        </a-popconfirm>
                      </a-tooltip>
                    </div>
                  </div>
                </div>
              </a-scrollbar>
            </div>
          </a-layout-sider>
        </a-layout>
      </div>
      <!-- <a-divider /> -->
      <div class="main-list">
        <ConditionBox :margin-bottom="20">
          <template #right>
            <a-button type="primary" @click="sessionShow = true"
              >新增离职原因</a-button
            >
            <a-button type="outline" @click="del(null)" status="danger"
              >批量删除</a-button
            >
          </template>
        </ConditionBox>
        <table-turn
          v-if="currId"
          ref="tableRef"
          :table-data="GetDimissionSession"
          stripe
          :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false
          }"
        >
          <a-table-column align="center" :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="300"
            dataIndex="reason"
            align="center"
            title="离职原因"
          ></a-table-column>
          <a-table-column
            :width="100"
            dataIndex="status"
            align="center"
            title="启用状态"
          >
            <template #cell="{ record }">
              <a-tag
                class="enable"
                :color="
                  record.enable === 1
                    ? `rgb(var(--green-1))`
                    : 'rgb(var(--danger-1))'
                "
                :style="{
                  color:
                    record.enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))',
                  '--enable':
                    record.enable === 1
                      ? `rgb(var(--green-6))`
                      : 'rgb(var(--danger-6))'
                }"
              >
                {{ record.enable === 1 ? '启用' : '停用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column
            title="操作"
            align="center"
            :width="150"
            fixed="right"
          >
            <template #cell="{ record }">
              <div v-if="item?.sysDefault !== 1">
                <a-tooltip content="编辑">
                  <icon-font
                    type="icon-edit"
                    :size="26"
                    @click="goEdit(record)"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                  />
                </a-tooltip>
                <a-tooltip content="删除" position="left">
                  <a-popconfirm
                    content="是否确认删除该条数据?"
                    @ok="del(record.id)"
                  >
                    <icon-font
                      type="icon-delete"
                      :size="26"
                      :style="{
                        cursor: 'pointer',
                        marginRight: '10px'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
              </div>
            </template>
          </a-table-column>
        </table-turn>
      </div>
    </div>
  </ContentCard>
  <!-- <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title> {{ typeData.id ? '编辑' : '新增' }}离职类型 </template>
    <a-form :model="typeData" :rules="rules">
      <a-form-item field="type" label="离职类型" required>
        <a-input v-model="typeData.leaveType" placeholder="请输入" />
      </a-form-item>
      <a-form-item>
        <span style="font-size: 12px; color: #999"
          >离职类型主要是为了区分员工是主动离职还是被动离职等
        </span>
      </a-form-item>
    </a-form>
  </a-modal> -->
  <a-modal :visible="sessionShow" @ok="sessionOK" @cancel="sessionCancel">
    <template #title> 新增离职原因 </template>
    <a-form :model="sessionData" ref="refForm" :rules="rules">
      <a-form-item field="leaveType" label="离职类型" show-colon>
        <!-- <a-select
          v-model="sessionData.leaveType"
          :options="typeList"
          :field-names="fieldNames"
          placeholder="请选择"
        /> -->
        <span> {{ typeList.find((el: any) => el.id === currId)?.name }} </span>
      </a-form-item>
      <a-form-item field="reason" label="离职原因" show-colon>
        <a-textarea
          v-model="sessionData.reason"
          placeholder="Please enter something"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <AddChangeType
    v-model:visible="addChangeTypeModalVisible"
    :data="currData"
    @changeAddTypeEmit="changeAddTypeEmit"
  />
</template>
<script setup lang="ts">
import {
  GetSession,
  DelSession,
  EditSession,
  PostDimission,
  PutDimission,
  RepeatSession,
  GetLeaveType,
  PostLeaveType,
  PutLeaveType,
  DelLeaveType
} from '@/apis/human/base/dimissionSetting/index';
import { LEAVE_TYPE } from '@/utils/constants';
import type {
  Page,
  dimissionType
} from '@/apis/human/base/dimissionSetting/type';
import { Message, Modal } from '@arco-design/web-vue';
import clonedeep from 'lodash.clonedeep';
import AddChangeType from './Components/AddChangeType/index.vue';

const refForm = ref();
const visible = ref(false);
const sessionShow = ref(false);
const tableRef = ref(); // 表格的ref
/* 储存选择的数据 */
const selectedList = ref<any>([]); // 储存选中的数据

let currId = ref(); // 储存左侧列表选中的id
let typeList = ref([]); // 异动类型列表

/**
 * 获取异动类型数据
 * @param isFirst 是否是进入页面的第一次请求
 */
const getTypeData = async (isFirst = false) => {
  try {
    const resp = await GetLeaveType();
    typeList.value = resp;
    if (isFirst) {
      currId.value = typeList.value[0].id;
      sessionData.value.leaveType = typeList.value[0].id;
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
getTypeData(true);

let isCollapsed = ref(false); // 判断是否收起

const collapse = (collapsed: boolean) => {
  isCollapsed.value = !isCollapsed.value;
};
const page = reactive<Page>({ page: 1, size: 10 });
const fieldNames = { value: 'key', label: 'label' };

const key = ref(1);
const session = ref();
const typeData = ref<dimissionType>({ leaveType: void 0 });
const sessionData = ref<dimissionType>({
  leaveType: currId.value,
  reason: '',
  enable: 1
});
const GetDimissionSession = async (pageData?: any) => {
  const res = await GetSession({
    ...pageData,
    type: currId.value
  });
  return Promise.resolve(res);
};

let addChangeTypeModalVisible = ref(false);
let currData = ref();
const addType = () => {
  currData.value = {};
  addChangeTypeModalVisible.value = true;
};

const changeAddTypeEmit = async (data: any) => {
  try {
    if (data.id) {
      await PutLeaveType(data);
    } else await PostLeaveType(data);
    getTypeData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 编辑类型
const goEditType = (record: any) => {
  currData.value = record;
  addChangeTypeModalVisible.value = true;
};

// 编辑类型
const delType = async (id: number) => {
  try {
    await DelLeaveType({
      id
    });
    getTypeData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 左侧item点击事件
const itemClick = (id: number) => {
  if (currId.value !== id) {
    currId.value = id;
    sessionData.value.leaveType = id;
    tableRef.value.loadData();
  }
};

const changeSession = async (id: number) => {
  key.value = id;
  await GetDimissionSession(id);
};

const editType = (data: dimissionType) => {
  visible.value = true;
  typeData.value = clonedeep(data);
};

const handleOk = async () => {
  if (typeData.value.id) {
    await EditSession(typeData.value);
  } else {
    await PostDimission(typeData.value);
  }
  typeData.value = { leaveType: void 0 };
};

const handleCancel = () => {
  typeData.value = { leaveType: void 0 };
};

const sessionCancel = () => {
  sessionShow.value = false;
  sessionData.value = { leaveType: void 0, reason: '', enable: 1 };
};
const sessionOK = async () => {
  const res = await refForm.value.validate();
  if (res) return;
  if (sessionData.value.id) {
    await PutDimission(sessionData.value);
  } else {
    await PostDimission(sessionData.value);
  }
  sessionShow.value = false;
  sessionData.value = { leaveType: void 0, reason: '', enable: 1 };
  init();
};
const del = async (id: number | null) => {
  try {
    if (!id) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              await DelSession({
                ids: selectedList.value
              });
              selectedList.value = [];
              init();
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      await DelSession({
        ids: [id]
      });
      selectedList.value = [];
      init();
    }
  } catch (error: unknown) {
    console.log(error);
  }
  await DelSession({ ids: [id] });
  init();
};
const changStatus = async (data: dimissionType) => {
  await EditSession(data);
  init();
};
const init = async () => {
  // await GetDimissionSession();
  tableRef.value.loadData();
};
let currReason = '';
const goEdit = (data: any) => {
  sessionShow.value = true;
  // Object.assign(sessionData.value, data);
  sessionData.value = data;
  currReason = data.reason;
  console.log('data', sessionData.value);
};
init();
const rules = {
  reason: [
    {
      required: true,
      message: '离职原因必填'
    },
    {
      validator: async (value: string, cb: any) => {
        try {
          console.log('=============sessionData=======================');
          console.log(sessionData.value);
          console.log('====================================');
          if (value === currReason && sessionData.value.id) {
            //
          } else {
            const res = await RepeatSession({
              reason: value,
              leaveType: sessionData.value.leaveType
            });
            if (res) cb(`${res.msg}`);
          }
        } catch (error: any) {
          console.log(error);
        }
      }
    }
  ]
};
</script>
<style lang="less" scoped>
.wrap {
  display: flex;
  .left-list {
    position: relative;
    // padding: 10px;
    padding: 15px;

    .collapseBtn {
      position: absolute;
      z-index: 9;
      top: 40%;
      right: 15px;
      height: 70px;
      width: 15px;
      background-color: #eee;
      line-height: 70px;
      text-align: center;
      cursor: pointer;
    }

    .layout-demo {
      height: 100%;
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 60px;
      border-bottom: 1px solid #ccc;
      .title {
        line-height: 60px;
        // position: relative;
        // right: 55px;
      }
      .title::before {
        position: relative;
        top: 5px;
        left: 10px;
        display: inline-block;
        height: 20px;
        width: 5px;
        margin-right: 20px;
        border-radius: 2px;
        content: '';
        background-color: #165dff;
      }
    }

    // height: 300px;
    .scroll {
      padding: 10px;

      &-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50px;
        padding: 0 10px;
        cursor: pointer;
      }
      &-item:hover {
        background-color: #f2f3f5;
        color: #165dff;
      }
    }
    .item-active {
      background-color: #f2f3f5;
      color: #165dff;
    }

    .item-active::before {
      position: absolute;
      display: inline-block;
      height: 50px;
      right: 0px;
      width: 5px;
      margin-right: 10px;
      border-radius: 2px;
      // transform: translateY(-50%);
      content: '';
      background-color: #165dff;
    }
  }

  .main-list {
    flex: 4;
    margin-left: 20px;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
